<template>
  <div
    class="echarts h-auto"
    :style="{ height: chartHeight ? chartHeight : '430px' }"
  >
    <ECharts
      v-if="option"
      :option="option"
      :id="`Line` + props.id"
      ref="lineEChartsRef"
      :onClick="handleClick"
    />
    <!-- 工单弹窗 -->
    <psmworkorder-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
      key="1"
    />
  </div>
</template>

<script lang="ts" setup>
import { getPieces, isGetPieces } from "@/views/pcm/pcmMonitoring/index";
import psmworkorderEdit from "@/views/pcm/psmworkorder/components/psmworkorder-edit.vue";
import request from "@/utils/request";
import Big from "big.js";
const props = defineProps({
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  showName: {
    type: Boolean,
    default: true,
  },
  // 曲线x轴/y轴数据
  seriesData: {
    type: Object,
    default: () => {},
  },
  chartHeight: {
    type: String,
    default: () => {
      return "430px";
    },
  },
  size: {
    type: String,
    default: () => {
      return "";
    },
  },
});
const { seriesData, showName, chartHeight, size } = toRefs(props);
const option = ref();
const lineEChartsRef = ref();

// 折线图数据变更
watch(
  () => seriesData.value,
  (newVal) => {
    if (newVal?.doubleData.length) {
      setOptions();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/psmworkorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
/** 打开工单管理表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "工单管理详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
function handleClick(param: any) {
  const id =
    seriesData.value.doubleData[param.componentIndex].workOrderData[
      param.dataIndex
    ] ?? "";
  if (id) {
    openDialogdetail({ id });
  }
}
// 计算y轴最小值
function computedMin(minValue: number, maxValue: number) {
  if (
    seriesData.value?.lowerLimitValue &&
    seriesData.value?.lowerLimitValue < minValue
  ) {
    return seriesData.value?.lowerLimitValue;
  } else if (minValue || maxValue) {
    const result = new Big(minValue)
      .minus(new Big(maxValue).minus(minValue).div(10))
      .toNumber()
      .toFixed(2);
    if (result < 0 && minValue >= 0) {
      return 0;
    } else {
      return result;
    }
  } else {
    return minValue;
  }
}

// 计算y轴最大值
function computedMax(maxValue: number, minValue: number) {
  if (!seriesData.value?.upperLimitValue && maxValue) {
    return new Big(maxValue)
      .plus(new Big(maxValue).minus(minValue).div(10))
      .toNumber()
      .toFixed(2);
  } else if (
    (minValue || maxValue) &&
    seriesData.value?.upperLimitValue &&
    seriesData.value?.upperLimitValue < maxValue
  ) {
    return new Big(maxValue)
      .plus(new Big(maxValue).minus(minValue).div(10))
      .toNumber()
      .toFixed(2);
  } else {
    return seriesData.value?.upperLimitValue;
  }
}

function setOptions() {
  const current = {
    animation: false,
    // animationDuration: 3 * 100,
    // tooltip: [],
    // color: ["#5470c6", "rgb(45, 93, 231)", "#15b3ff", "rgb(69,108,244)"],
    tooltip: {
      trigger: "axis",
      formatter: function (value) {
        return formatterTxt(value);
      },
      textStyle: {
        align: "left",
        fontSize: 14,
        fontFamily: "DINAlt",
        lineHeight: 30,
      },
    },
    legend: {
      show: true,
      bottom: "0%",
    },
    grid: {
      left: "20",
      top: "70",
      right: size.value === "small" ? 20 : 60,
      height: "auto",
      // minHeight: 400, // 单位为像素
      bottom: "10%",
      containLabel: true,
    },
    title: {
      text: seriesData.value.paramName || "",
      textStyle: {
        align: "center",
        fontSize: size.value === "small" ? 15 : 16,
        fontFamily: "DINLight",
      },
      top: "3%",
      left: "center",
    },
    xAxis: {
      type: "category",
      data: seriesData.value.doubleData[0].xdataIndex || [],
      // data: seriesData.value.xdata || [],
      axisLabel: {
        interval: "auto", // 坐标刻度之间的显示间隔，默认就可以了
        // rotate: 38, // 调整数值改变倾斜的幅度（范围-90到90）
        fontSize: 13,
        fontFamily: "DINLight",
      },
      axisTick: {
        alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
      },
    },
    yAxis: {
      type: "value", // 坐标轴类型:数值轴
      // name: "湿度", // 坐标轴名称
      boundaryGap: false,
      // scale: true,
      min: function (value: any) {
        return computedMin(value.min, value.max);
      },
      max: function (value: any) {
        return computedMax(value.max, value.min);
      },
      position: "left", // 坐标轴位置:左侧
      // axisLabel: {
      //   interval: "auto", // 坐标刻度之间的显示间隔，默认就可以了
      //   // 调整数值改变倾斜的幅度（范围-90到90）
      // },
      // interval: "auto", // 坐标轴刻度间隔(当前被注释掉)
      offset: 0, // 坐标轴相对于默认位置的偏移:无偏移
      axisLine: {
        show: true, // 是否显示坐标轴线
        lineStyle: {
          color: "#6e7079", // 坐标轴线颜色:使用颜色数组的第一个颜色
        },
      },
      axisLabel: {
        fontSize: 13,
        fontFamily: "DINLight",
        // 自定义标签显示：当布尔类型图表，则显示 true or false
        formatter: function (value: number) {
          return value;
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        show: true, // 是否显示分隔线
        lineStyle: {
          type: "dotted", // 分隔线类型:点线
        },
      },
    },
    dataZoom: [
      // {
      //   type: "slider", // 滑动条型数据区域缩放
      //   start: 0,
      //   end: 100,
      // },
      {
        type: "inside", // 内置型数据区域缩放
        start: 0,
        end: 100,
      },
    ],
    series: [],
  };
  seriesData.value.doubleData.map((item: any, index) => {
    const obj = {
      name: `${item.equipName || ""}`,
      type: "line",
      data: item.ydata || [],
      markPoint: {
        data: [
          {
            type: "max",
          },
          {
            type: "min",
          },
        ],
      },
      // markLine: {
      //   silent: true,
      //   data: [
      //     {
      //       name: "",
      //       yAxis: `${item?.parameterStandards || null}`,
      //       lineStyle: {
      //         color: "rgb(29, 233, 182)",
      //         type: "dashed",
      //         width: 1,
      //       },
      //       label: {
      //         show: true,
      //         position: "end",
      //         formatter: "标准线",
      //       },
      //     },
      //     {
      //       name: "",
      //       yAxis: `${item?.controlUp || null}`,
      //       lineStyle: {
      //         color: "#ffd300",
      //         type: "dashed",
      //         width: 1,
      //       },
      //       label: {
      //         show: true,
      //         position: "end",
      //         formatter: "预警上限",
      //       },
      //     },
      //     {
      //       name: "",
      //       yAxis: `${item?.controlDown || null}`,
      //       lineStyle: {
      //         color: "#ffd300",
      //         type: "dashed",
      //         width: 1,
      //       },
      //       label: {
      //         show: true,
      //         position: "end",
      //         formatter: "预警下限",
      //       },
      //     },
      //   ],
      //   symbol: "none",
      // },
      symbol: "circle",
      symbolSize: 6,
      lineStyle: {
        width: 1,
      },
    };
    current.series.push(obj);
  });
  option.value = current;
}

function formatterTxt(value) {
  let txt = `第${value[0].axisValueLabel}个节点`;
  value?.map((item, index) => {
    if (item.data) {
      txt +=
        `<br />` +
        `${item.marker}${item.seriesName}&nbsp;&nbsp;&nbsp;&nbsp;` +
        `${item.data}` +
        `<br />` +
        `<span style=\"padding-left:10px;font-family:DINLight;font-size:13px;\">${
          seriesData.value.doubleData[index]?.xdata[item.dataIndex]
        }</span>`;
    }
  });
  return txt;
}

onMounted(() => {});
</script>

<style lang="scss" scoped>
.echarts {
  width: 100%;
  height: 430px;
}

.echarts:nth-last-child(1) {
  border-bottom: none !important;
}
</style>
